package com.zzptc.myk.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zzptc.myk.myapplication.Bean.Book;
import com.zzptc.myk.myapplication.Bean.User;

import org.litepal.LitePal;

public class LoginActivity extends AppCompatActivity {
    private EditText usnedit,psdedit;
    private Button loginbtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getBook();
        getUser();
        initView();
        setListener();
    }

    private void getBook() {
        new Book(0,"重生之大国工匠","和光万物",R.mipmap.a).save();
        new Book(0,"我的前任全是巨星","葆星",R.mipmap.b).save();
        new Book(0,"我在农村修个仙","九驰",R.mipmap.c).save();
        new Book(0,"我有一座野生动物园","可口的橘子",R.mipmap.e).save();
        new Book(0,"神豪生活妙啊","这就是生活吧",R.mipmap.e).save();
        new Book(0,"离婚后我走上了华娱之巅","熊半生",R.mipmap.f).save();
        new Book(0,"半岛小导游","我是渣渣杰",R.mipmap.g).save();
    }

    private void getUser() {
        new User(0,"张三","123").save();
        new User(0,"李四","123").save();
        new User(0,"a","123").save();
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usnedit.getText().toString().trim();
                String psd=psdedit.getText().toString().trim();
                User u=confirmUser(usn,psd);
                if (u==null){

                }else {
                    Intent it=new Intent(LoginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("userid",u.getId());
                    editor.putString("username",u.getUsername());
                    editor.apply();
                    startActivity(it);
                }
            }
        });
    }

    private User confirmUser(String usn, String psd) {
       for (User u: LitePal.findAll(User.class)) {
           Log.e("user",u.getUsername()+u.getPassword());
           if (u.getUsername().equals(usn) && u.getPassword().equals(psd)) {
               return u;
           }
       }
        return null;
    }

    private void initView() {
        usnedit=findViewById(R.id.usnedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);
    }
}
